package com.dtm.ui;

import java.util.ArrayList;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicBoolean;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;

import com.dtm.R;
import com.dtm.adapter.AdapterUser;
import com.dtm.client.Client;
import com.dtm.client.ClientConnectedThread;
import com.dtm.client.thread.EndGameListener;
import com.dtm.client.thread.UpdateListListener;
import com.dtm.model.User;
import com.dtm.server.ServerThread;

public class InRoomActivity extends Activity implements UpdateListListener,
		EndGameListener {
	private ListView lvPlayer;

	private AdapterUser adapterUser;

	private Handler handler = new Handler();

	private ServerThread serverThread;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_inroom);
		Intent intent = getIntent();
		if (intent.getIntExtra("key", 3) == MainActivity.CLIENT_ACTIVITY) {
			ClientConnectedThread connectThread = new ClientConnectedThread(
					SearchHost.ipAdress, SearchHost.port, this, handler,
					getApplicationContext(), this);
			new Thread(connectThread).start();
		} else if (intent.getIntExtra("key", 3) == MainActivity.HOST_ACTIVITY) {
			serverThread = new ServerThread(handler, MainActivity.userName,
					this, getApplicationContext(), this);
			serverThread.start();
		}

		lvPlayer = (ListView) findViewById(R.id.lv_player);
		adapterUser = new AdapterUser(getApplicationContext(), -1,
				new Vector<Client>());
		lvPlayer.setAdapter(adapterUser);
	}

	public void onBackPressed() {
		if (null != serverThread) {
			serverThread.stopServer();
		}
		super.onBackPressed();
	}



	@Override
	public void onListChange(Vector<Client> clientVector) {
		adapterUser.clear();
		for (Client client : clientVector) {
			adapterUser.add(client);
			adapterUser.notifyDataSetChanged();
		}
	}

	@Override
	public void onEndGame(String loserName) {
		Intent intent = new Intent(InRoomActivity.this, EndGameActivity.class);
		intent.putExtra("loserName", loserName);
		startActivity(intent);
		finish();
	}

}
